/********************************************************************************
 * Project Name		[JavaEE_Web]
 * File Name     	[TestJNDI.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package servlet.other;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 * 测试JNDI
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
@WebServlet(name = "TestJNDI", urlPatterns = "/jndi")
public class TestJNDI extends HttpServlet {

	private static final long serialVersionUID = 6582402955277499003L;

	@Override
	public void init() throws ServletException {
		try {
			// 初始化JNDI
			Context initialContext = new InitialContext();
			// 得到JNDI容器
			Context envContext = (Context) initialContext.lookup("java:comp/env");
			// 从JNDI容器中检索name为jdbc/JavaEE_Web的数据源
			DataSource dataSource = (DataSource) envContext.lookup("jdbc/JavaEE_Web");
			// 获得连接
			Connection connection = dataSource.getConnection();
			System.out.println("Get Connection From DataSource --->" + connection);
		} catch (NamingException | SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}
}
